package com.it.flowable.model;

import com.it.flowable.listener.AdvancedFlowableListener;
import com.it.flowable.listener.MyExecutionListener;
import com.it.flowable.listener.MyTaskListener;
import com.it.flowable.util.DataUtils;
import com.it.flowable.util.ExtensionElementUtils;
import com.it.flowable.util.Utils;
import com.it.flowable.util.ListenerUtils;
import org.flowable.bpmn.model.*;
import org.flowable.bpmn.model.Process;

import java.util.*;

public class TestUserTaskModel {

    // 流程常量
    public static final String PROCESS_KEY = "TestUserTaskModel";
    public static final String PROCESS_NAME = "TestUserTaskModel";

    // 节点ID
    public static final String START_EVENT = "start";
    public static final String APPLY_TASK = "applyTask";
    public static final String LEADER_APPROVAL = "leaderApproval";
    public static final String END_EVENT = "end";

    public static final List<FormProperty> SUBMIT_FORM_PROPERTIES = DataUtils.createSubmitFormProperties();
    public static final List<FormProperty> APPROVAL_FORM_PROPERTIES = DataUtils.createApprovalFormProperties();

    /**
     * 创建简化的请假审批流程
     */
    public static BpmnModel create() {
        BpmnModel model = new BpmnModel();
        Process process = new Process();
        process.setId(PROCESS_KEY);
        process.setName(PROCESS_NAME);
        model.addProcess(process);

        // 创建并添加所有节点
        Event startEvent = Utils.createStartEvent(START_EVENT, "开始事件", null, null, null, null);
        UserTask submitTask = Utils.createUserTask(APPLY_TASK, "填写请假申请", "${initiator}", "APPLY", SUBMIT_FORM_PROPERTIES, null, null);
        UserTask leaderTask = addLeaderTask(LEADER_APPROVAL, "直属领导审批", "${leaderAssignee}", "APPROVAL", APPROVAL_FORM_PROPERTIES);
        Event endEvent = Utils.createEndEvent(END_EVENT, "结束事件");

        // 创建序列流
        SequenceFlow flow = Utils.createSequenceFlow(START_EVENT, APPLY_TASK, "提交申请", null, null);
        SequenceFlow flow1 = Utils.createSequenceFlow(APPLY_TASK, LEADER_APPROVAL, "提交审批", null, null);
        SequenceFlow flow2 = Utils.createSequenceFlow(LEADER_APPROVAL, END_EVENT, "审批完成", null, null);

        process.addFlowElement(startEvent);
        process.addFlowElement(submitTask);
        process.addFlowElement(leaderTask);
        process.addFlowElement(endEvent);
        process.addFlowElement(flow);
        process.addFlowElement(flow1);
        process.addFlowElement(flow2);

        return model;
    }

    public static UserTask addLeaderTask (String id, String name, String assignee, String category, List<FormProperty> formProperties) {
            String executionListener = MyExecutionListener.class.getName();
        String taskListener = MyTaskListener.class.getName();

        // 2. 直属领导审批
        UserTask leaderTask = new UserTask();
        leaderTask.setId(id);
        leaderTask.setName(name);
        leaderTask.setAssignee(assignee);
        leaderTask.setCategory(category);

        leaderTask.setId("approvalTask");
        leaderTask.setName("部门审批");

        // 设置负责人
        leaderTask.setAssignee("${departmentManager}");

        // 设置候选人
        leaderTask.getCandidateUsers().add("user1");
        leaderTask.getCandidateUsers().add("user2");
        leaderTask.getCandidateGroups().add("deptLeaders");

        // 设置优先级
        leaderTask.setPriority("75");

        // 设置表单
        leaderTask.setFormKey("deptApprovalForm");

        // 设置到期时间（3天后）
        leaderTask.setDueDate("${now()+P3D}");

        // 添加表单属性
        for (FormProperty formProperty : formProperties) {
            leaderTask.getFormProperties().add(formProperty);
        }

        // 添加任务监听器
        FlowableListener listener = ListenerUtils.createFlowableListener("complete", taskListener, ImplementationType.IMPLEMENTATION_TYPE_CLASS);
        leaderTask.getTaskListeners().add(listener);

        ExtensionElement extensionElement = ListenerUtils.createExecutionListener("end", executionListener, ImplementationType.IMPLEMENTATION_TYPE_CLASS);

        leaderTask.getExtensionElements()
                .computeIfAbsent("executionListener", k -> new ArrayList<>())
                .add(extensionElement);

        List<Map<String, String>> dataList = AdvancedFlowableListener.MessageType.getMap();

        for (Map<String, String> map : dataList) {
            ExtensionElement notifyElement = ExtensionElementUtils.createExtensionElement(map, "notify");
            leaderTask.getExtensionElements()
                    .computeIfAbsent("notify", k -> new ArrayList<>())
                    .add(notifyElement);
        }

        // 设置自定义身份链接
        leaderTask.getCustomUserIdentityLinks().put("reviewer",  new HashSet<>(Arrays.asList("user1", "user2")));

        // 设置跳过表达式
        leaderTask.setSkipExpression("${autoComplete == true}");

        // 设置任务ID变量名
        leaderTask.setTaskIdVariableName("currentTaskId");

        // 设置业务日历
        leaderTask.setBusinessCalendarName("chineseHolidayCalendar");


        return leaderTask;
    }
}